package com.mikufufu.blog.listener;

import com.mikufufu.blog.common.constant.ListenerTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听器工厂
 */
@Slf4j
@Component
public class ListenerFactory {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 获取所有实现BaseListener接口的监听器
     * @return 实现BaseListener接口的监听器
     */
    private Map<String, BaseListener> getListenerImpl() {
        return applicationContext.getBeansOfType(BaseListener.class);
    }

    /**
     * 设置监听器
     * @param container 监听器容器
     */
    public void setListeners(RedisMessageListenerContainer container){
        log.debug("开始监听...");
        Map<String, BaseListener> map = this.getListenerImpl();
        // 添加所有实现BaseListener接口的监听器
        for (BaseListener listener : map.values()) {
            // 0：channel 1：pattern
            if (listener.topicType() == ListenerTopic.CHANNEL) {
                container.addMessageListener(listener,new ChannelTopic(listener.getTopic()));
                log.debug("监听器：{}，监听的channel：{}", listener.getClass().getName(), listener.getTopic());
            } else if (listener.topicType() == ListenerTopic.PATTERN){
                container.addMessageListener(listener,new PatternTopic(listener.getTopic()));
                log.debug("监听器：{}，监听的pattern：{}", listener.getClass().getName(), listener.getTopic());
            }
        }
    }

}
